package kontroler;

import interfejs.AddOwnersFrame;
import interfejs.OwnersPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;


import viewModel.OwnersTableModel;

import Model.Baza;
import Model.Wlasciciel;





public class OwnersPanelController extends Controller implements ActionListener, TableModelListener, ListSelectionListener {

	private static OwnersPanel pannel;
	@Override
	public void valueChanged(ListSelectionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void tableChanged(TableModelEvent e) {
		
		// TODO Auto-generated method stub
		if(e.getType() == TableModelEvent.UPDATE){
			System.out.println("Poszedl UPDATE");
			int row = e.getFirstRow();
	        int column = e.getColumn();
	        OwnersTableModel model = (OwnersTableModel)e.getSource();
	        if(row < 0 || column < 0)
	        	return;
	        Object data = model.getValueAt(row, column);
	        Object id = model.getValueAt(row, 0);
	        Wlasciciel tempOwner = Baza.getWlascicieleStatic().getById(id.toString());
	        
	        switch(column){
		        case 1:
		        	tempOwner.setImie((String) data);
		        break;
		        case 2:
		        	tempOwner.setNazwisko((String) data);
		        break;
	        }
	        System.out.println(tempOwner);
	        
	        System.out.println(row + " " + column+" "+ data +" " + id);
		}
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getActionCommand().equals("NEW_OWNER")){
			pannel = ((OwnersPanel)((JToolBar)((JButton) e.getSource()).getParent()).getParent());
			pannel.setAddOwnersFrame(new AddOwnersFrame());
			pannel.getAddOwnersFrame().createGUI();
			
		} else if(e.getActionCommand().equals("ADD_OWNER")){
			AddOwnersFrame frame = (AddOwnersFrame) ((JButton) e.getSource()).getTopLevelAncestor();
			Baza.getWlascicieleStatic().addOwner(frame.getClientName().getText(), frame.getClientSurName().getText());
			if(pannel != null){
				pannel.getOwnersTableModel().setTable(Baza.getWlascicieleStatic());
				pannel.getOwnersTable().repaint();
				pannel = null;
			}
			
			frame.dispose();
			
		}
		
	}

}
